﻿using SqliteTest1;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace SqliteShow
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        static Program program = null;

        public DataSet MyDataSet
        {
            get { return (DataSet)GetValue(MyDataSetProperty); }
            set { SetValue(MyDataSetProperty, value); }
        }

        public static readonly DependencyProperty MyDataSetProperty =
            DependencyProperty.Register("MyDataSet", typeof(DataSet), typeof(MainWindow), new PropertyMetadata());


        public DataTable MyDataTable
        {
            get { return (DataTable)GetValue(MyDataTableProperty); }
            set { SetValue(MyDataTableProperty, value); }
        }

        public static readonly DependencyProperty MyDataTableProperty =
            DependencyProperty.Register("MyDataTable", typeof(DataTable), typeof(MainWindow), new PropertyMetadata());

        public MainWindow()
        {
            InitializeComponent();
            base.DataContext = this;

            program = new Program();
            MyDataSet = program.GetAsDataTable();
            MyDataTable = MyDataSet.Tables[0];
        }

        private void Save(object sender, RoutedEventArgs e)
        {
            if (program.SaveChangesToDatabase(MyDataSet, "mytabel01") == 0)
            {
                MessageBox.Show("数据未变更");
            }
            else
            {
                MessageBox.Show("保存成功");
                MyDataSet = program.GetAsDataTable();
                MyDataTable = MyDataSet.Tables[0];
            }
        }

        private void Add(object sender, RoutedEventArgs e)
        {
            var row = MyDataTable.NewRow();
            MyDataTable.Rows.Add(row);
        }

        private void Delete(object sender, RoutedEventArgs e)
        {
            var menuItem = sender as MenuItem;
            if (menuItem != null && menuItem.Parent is ContextMenu contt
                && contt.PlacementTarget is DataGrid dataGrid)
            {
                var dataRowView = dataGrid.SelectedItem as DataRowView;
                var idnex = MyDataTable.Rows.IndexOf(dataRowView.Row);
                var dataRow = MyDataTable.Rows[idnex];
                dataRow.Delete();
            }
        }
    }
}
